#include "Insert.h"
#include "Config.h"
#include "IndexGenerator.h"
#include "Utility.h"

#include <stdio.h>
#include <assert.h>

void insertx
(
    char* sourceRelation, 
    int* tuple
)
{
    int segmentNumber = SEGMENTS_COUNT - 1;

    char* segmentName = getSegmentName(sourceRelation, segmentNumber);

    FILE* binFile = 
        fopen(getFileNameByRelationNameWithExtension(segmentName,"bin"),"ab");
    setbuf (binFile, NULL);
    fseek(binFile, 0, SEEK_END); 
    long tuplesCount = ftell(binFile)/(ARITY * sizeof(int));

    if (tuplesCount >= TUPLES_IN_FULL_SEGMENT)
    {
        fclose(binFile);
        SEGMENTS_COUNT += 1;
        segmentNumber = SEGMENTS_COUNT - 1;

        segmentName = getSegmentName(sourceRelation, segmentNumber);
        binFile = 
            fopen(getFileNameByRelationNameWithExtension(segmentName,"bin"),"wb");
        setbuf (binFile, NULL);
    }

    fwrite(tuple,sizeof(int)*ARITY,1,binFile);
    fclose(binFile);
    generateIndex(getSegmentName("R", segmentNumber),TUPLES_IN_FULL_SEGMENT);
}

void insert
(
    char* sourceRelation, 
    int* tuple,
    bool isIndexed
 )
{
    FILE* binFileIn = 
        fopen(getFileNameByRelationNameWithExtension(sourceRelation),"ab");
    assert(binFileIn != NULL);
    setbuf (binFileIn, NULL);
    fseek(binFileIn, 0, SEEK_END); 
    fwrite(tuple,sizeof(int)*ARITY,1,binFileIn); 
    R_SIZE += 1;
    fclose(binFileIn);

    if (isIndexed)
    {
        generateIndex("R", R_SIZE);
    }

}